<template>
  <div class="app-container">
    <el-container>
      <el-header >
        <el-row :gutter="5" style="padding-top: 15px">
          <!--           左     -->
          <el-col :span="8" align="left">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['jbxx:attribute:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['jbxx:attribute:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['jbxx:attribute:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['jbxx:attribute:export']"
                >导出</el-button>
              </el-col>
            </el-row>
          </el-col>
          <!--           右     -->
          <el-col :span="16" align="right" >
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
              <el-form-item prop="sxName">
                <el-input
                  v-model="queryParams.sxName"
                  placeholder="请输入关键字"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-header>

      <el-main>
        <el-table v-loading="loading" :data="attributeList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" :index="indexMethod" />
          <el-table-column label="属性编码" align="center" prop="sxCode" />
          <el-table-column label="属性名称" align="center" prop="sxName" />
          <el-table-column label="属性类型" align="center" prop="sxTypeCode">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.attribute_type" :value="scope.row.sxTypeCode"/>
            </template>
          </el-table-column>
          <el-table-column label="属性值" align="center" prop="sx_value" />
          <el-table-column label="所属分类产品" align="center" prop="cpfl_name" />
          <el-table-column label="启用" align="center" key="isStart" v-if="columns[0].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isStart"
                active-value="true"
                inactive-value="false"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['jbxx:attribute:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['jbxx:attribute:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>

      <el-footer>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-footer>
    </el-container>


    <!-- 添加或修改属性值对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="属性名称" prop="sxName">
              <el-input v-model="form.sxName" placeholder="请输入属性名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="属性类型" prop="sxTypeCode">
              <el-select v-model="form.sxTypeCode" placeholder="请选择属性类型">
                <el-option
                  v-for="dict in dict.type.attribute_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-divider content-position="center">属性值</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSxAttributeValue">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSxAttributeValue">删除</el-button>
          </el-col>
        </el-row>

        <el-table border stripe :data="sxAttributeValueList" :row-class-name="rowSxAttributeValueIndex" @selection-change="handleSxAttributeValueSelectionChange" ref="sxAttributeValue">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50px" />
          <el-table-column label="属性值" prop="sxValue" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.sxValue"  placeholder="请输入属性值" @blur="validateInput(scope.row)" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="center">关联产品分类</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSxAttributeValueCpType">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSxAttributeValueCpType">删除</el-button>
          </el-col>
        </el-row>
        <el-table border stripe :data="sxAttributeValueListCpType" :row-class-name="rowSxAttributeValueIndexCpType" @selection-change="handleSxAttributeValueSelectionChangeCpType" ref="sxAttributeValueListCpType">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50px" />
          <el-table-column label="产品分类名称" prop="cpflName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.cpflName" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--     选择产品分类    -->
    <el-dialog title="选择产品分类" :visible.sync="dialogTableVisibleHead">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

        <el-row>
          <el-col :span="8">
            <div>
              <el-form-item  prop="cpflName">
                <el-input
                  v-model="queryParams.cpflName"
                  placeholder="关键字筛选"
                  clearable
                  @keyup.enter.native="handleQueryChangeFactory"
                />
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="16">
            <div align="right">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryChangeFactory" style="background-color: rgba(0,176,192);color: #FFFFFF">查询</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

      </el-form>

      <el-table border stripe :data="sxAttributeValueCpflList" ref="multipleTableFactory" @selection-change="handleSelectionChangeFactory">
        <el-table-column type="selection" width="55" align="center"  />
        <el-table-column property="cpflCode" label="产品分类编码" ></el-table-column>
        <el-table-column property="cpflName" label="产品分类名称"></el-table-column>
      </el-table>

      <el-row :gutter="5">
        <el-col :span="24" align="right">
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer" align="center" style="padding-top: 20px">
        <el-button @click="cancelFactory" style="background-color: rgba(0,176,192);color: #FFFFFF">取 消</el-button>
        <el-button type="primary" @click="submitFormFactory">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listAttribute, getAttribute, delAttribute, addAttribute, updateAttribute , listAttributeCpfl , updateAttributeIsStart , getCpAttribute} from "@/api/jbxx/attribute";

export default {
  name: "Attribute",
  dicts: ['attribute_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSxAttributeValue: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 属性值表格数据
      attributeList: [],
      attributeListSxValue: null,
      // 属性值添加的表格数据
      sxAttributeValueList: [],
      // 产品分类值表格数据
      sxAttributeValueListCpType: [],
      // 产品分类值添加表格数据
      sxAttributeValueCpflList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sxName: null,
        isStart: null,
        sxAttributeValueList:[],
        sxAttributeValueListCpType:[],
        cpflProductClassifications:[],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sxName: [
          { required: true, message: "属性名称不能为空", trigger: "blur" }
        ],
        sxTypeCode: [
          { required: true, message: "属性类型不能为空", trigger: "change" }
        ],
      },
      dialogTableVisibleHead:false,
      selectedRow:[],
      // 列信息
      columns: [
        { key: 0, label: `启用`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
    this.getCpflList();
  },
  methods: {
    /** 查询属性值列表 */
    getList() {
      this.loading = true;
      listAttribute(this.queryParams).then(response => {

        for (let i = 0; i < response.rows.length; i++) {
          response.rows[i].isStart = response.rows[i].isStart === 1 ? 'true' : 'false';
        }

        this.attributeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询分类值列表 */
    getCpflList() {
      listAttributeCpfl(this.queryParams).then(response => {
        this.sxAttributeValueCpflList = response.rows;
        this.total = response.total;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        sxCode: null,
        sxName: null,
        sxTypeCode: null,
        isStart: null,
        isDelete: null
      };
      this.sxAttributeValueList = [];
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 产品分类搜索按钮操作 */
    handleQueryChangeFactory() {
      this.queryParams.pageNum = 1;
      this.getCpflList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sxCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 属性序号 */
    indexMethod(index) {
      return index + 1 ;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增属性值";
      this.sxAttributeValueListCpType = null;
      this.queryParams.cpflName = null;
      this.selectedRow = null;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sxCode = row.sxCode || this.ids
      getAttribute(sxCode).then(response => {
        return  response;
      }).then(response=>{
        getCpAttribute(sxCode).then(responses=>{
          this.form = response.data;
          this.sxAttributeValueList = response.data.sxAttributeValueList;
          this.sxAttributeValueListCpType = responses.data.cpflProductClassifications;
          this.open = true;
          this.queryParams.cpflName = null;
          this.selectedRow = null;
          this.title = "编辑属性值";
        })
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.sxAttributeValueList.length==0){
            this.$message.error('属性值不能为空，请添加属性值！');
            return false;
          }

          if (this.sxAttributeValueListCpType.length==0){
            this.$message.error('产品分类不能为空，请添加分类值！');
            return false;
          }

          this.form.sxAttributeValueList = this.sxAttributeValueList;
          this.form.sxAttributeValueListCpType = this.sxAttributeValueListCpType;
          if (this.form.sxCode != null) {
            updateAttribute(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttribute(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const sxCodes = row.sxCode || this.ids;
      this.$modal.confirm('是否确认删除属性值编号为"' + sxCodes + '"的数据项？').then(function() {
        return delAttribute(sxCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 属性值序号 */
    rowSxAttributeValueIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 产品分类值序号 */
    rowSxAttributeValueIndexCpType({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },

    /** 产品分类添加按钮操作 */
    handleAddSxAttributeValueCpType() {
      this.open = false;
      this.dialogTableVisibleHead = true;
      this.$nextTick(() => {
        if (this.sxAttributeValueListCpType != null) {
          this.selectRowById(this.sxAttributeValueListCpType);
        }
      });
    },

    /** 产品分类修改默认选择 */
    selectRowById(sxAttributeValueListCpType) {
      // 确保sxAttributeValueListCpType是数组
      if (!Array.isArray(sxAttributeValueListCpType)) {
        console.error('Expected an array for sxAttributeValueListCpType');
        return;
      }

      // 初始化一个空数组用于存储需要选中的行
      let rowsToSelect = [];

      // 遍历sxAttributeValueListCpType数组
      for (let i = 0; i < sxAttributeValueListCpType.length; i++) {
        const cpflName = sxAttributeValueListCpType[i].cpflName;

        // 再次遍历this.sxAttributeValueCpflList数组
        for (let j = 0; j < this.sxAttributeValueCpflList.length; j++) {
          const item = this.sxAttributeValueCpflList[j];

          // 检查当前item的cpflName是否与sxAttributeValueListCpType中的cpflName匹配
          if (item.cpflName === cpflName) {
            // 如果匹配，则将item添加到rowsToSelect数组中
            rowsToSelect.push(item);
            break; // 找到匹配项后跳出内层循环
          }
        }
      }

      if (rowsToSelect.length > 0) {
        for (let i = 0; i < rowsToSelect.length; i++) {
          this.$refs.multipleTableFactory.toggleRowSelection(rowsToSelect[i]);
          this.selectedRow = rowsToSelect[i];
        }
      }
    },

    /** 分类删除按钮操作 */
    handleDeleteSxAttributeValueCpType() {
      if (this.checkedSxAttributeValue.length == 0) {
        this.$modal.msgError("请先选择要删除的属性值数据");
      } else {
        const sxAttributeValueListCpType = this.sxAttributeValueListCpType;
        const checkedSxAttributeValue = this.checkedSxAttributeValue;
        this.sxAttributeValueListCpType = sxAttributeValueListCpType.filter(function(item) {
          return checkedSxAttributeValue.indexOf(item.index) == -1
        });
      }
    },

    /** 属性值添加按钮操作 */
    handleAddSxAttributeValue() {
      let obj = {};
      obj.sxValue = "";
      this.sxAttributeValueList.push(obj);
    },

    /** 属性值删除按钮操作 */
    handleDeleteSxAttributeValue() {
      if (this.checkedSxAttributeValue.length == 0) {
        this.$modal.msgError("请先选择要删除的属性值数据");
      } else {
        const sxAttributeValueList = this.sxAttributeValueList;
        const checkedSxAttributeValue = this.checkedSxAttributeValue;
        this.sxAttributeValueList = sxAttributeValueList.filter(function(item) {
          return checkedSxAttributeValue.indexOf(item.index) == -1
        });
      }
    },

    /** 复选框选中数据 */
    handleSxAttributeValueSelectionChange(selection) {
      this.checkedSxAttributeValue = selection.map(item => item.index)
    },

    /** 复选框选中数据 */
    handleSxAttributeValueSelectionChangeCpType(selection) {
      this.checkedSxAttributeValue = selection.map(item => item.index)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('jbxx/attribute/export', {
        ...this.queryParams
      }, `attribute_${new Date().getTime()}.xlsx`)
    },

    /** 产品分类多选框选中数据 */
    handleSelectionChangeFactory(selection) {

      this.ids = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length

      if (this.title == "新增属性值") {
        this.sxAttributeValueListCpType = selection;
      } else {
        for (let i = 0; i < selection.length; i++) {
          const selectedElement = selection[i];
          const exists = this.sxAttributeValueListCpType.some(item => item.cpflName === selectedElement.cpflName);

          if (!exists) {
            this.sxAttributeValueListCpType.push(selectedElement);
          }
        }
      }
    },

    /**产品分类取消*/
    cancelFactory() {
      this.dialogTableVisibleHead=false;
      this.open = true;
      this.$refs.multipleTableFactory.clearSelection();
      if (this.title=="新增属性值"){
        if (this.sxAttributeValueListCpType != null){
          this.selectedRow = null;
          this.sxAttributeValueListCpType=undefined
        }
      }
    },

    /** 产品分类提交 */
    submitFormFactory(){
      this.dialogTableVisibleHead = false;
      this.open = true;
      if (this.title=='新增属性值'){
        this.selectedRow = null;
      }
    },

    /** 产品属性状态修改 */
    handleStatusChange(row) {

      let text = row.isStart === "true" ? "启用" : "停用";

      let isStart = row.isStart === "true" ? "1" : "0";
      this.$modal.confirm('确认要"' + text + '""' + row.sxName + '"用户吗？').then(function()
      {

        return updateAttributeIsStart(row.sxCode, isStart);

      }).then(() => {

        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {

        row.isStart = row.isStart === "true" ? "1" : "0";
      });
    },
    validateInput(row) {
      if (!row.sxValue.trim()) {
        this.$message.error('属性值不能为空，请输入属性值！');
        return false;
      }
    },
  }
};
</script>

<style>
/*弹出框圆角边框样式*/
.el-dialog{
  border-radius: 20px;
}

.el-message--warning {
  background-color: #fff3cd; /* 警告消息背景色 */
  color: #856f00; /* 警告消息文本颜色 */
  border-color: #ffe68a; /* 警告消息边框颜色 */
}

.el-message__content {
  color: red; /* 修改警告消息内容的颜色 */
}
</style>
